#include "common/pch.h"
#include "map/poolmgr.h"

#include <format>
#include <sstream>

#include <cftf/loger/syslog.h>
#include <cftf/mysql/dbpool.h>

#include "metadata/pool_template.h"
#include "metadata/pool_creature.h"
#include "metadata/pool_creature_template.h"
#include "metadata/pool_gameobject.h"
#include "metadata/pool_gameobject_template.h"
#include "metadata/pool_pool.h"
#include "metadata/gameobjectdata.h"
#include "metadata/creaturedata.h"
#include "metadata/gameobject_info.h"
#include "world/world.h"
#include "map/terrainmgr.h"
#include "util/util.h"
#include "map/map_persistent_state_mgr.h"
#include "map/map.h"
#include "object/creature.h"
#include "object/gameobject.h"

// Method that tell amount spawned objects/subpools
unsigned int SpawnedPoolData::GetSpawnedObjects(unsigned int pool_id) const
{
    SpawnedPoolPools::const_iterator itr = mSpawnedPools.find(pool_id);
    return itr != mSpawnedPools.end() ? itr->second : 0;
}

// Method that tell if a creature is spawned currently
template<>
bool SpawnedPoolData::IsSpawnedObject<battle::object::Creature>(unsigned int db_guid) const
{
    return mSpawnedCreatures.find(db_guid) != mSpawnedCreatures.end();
}

// Method that tell if a gameobject is spawned currently
template<>
bool SpawnedPoolData::IsSpawnedObject<battle::object::GameObject>(unsigned int db_guid) const
{
    return mSpawnedGameobjects.find(db_guid) != mSpawnedGameobjects.end();
}

// Method that tell if a pool is spawned currently
template<>
bool SpawnedPoolData::IsSpawnedObject<Pool>(unsigned int sub_pool_id) const
{
    return mSpawnedPools.find(sub_pool_id) != mSpawnedPools.end();
}

template<>
void SpawnedPoolData::AddSpawn<battle::object::Creature>(unsigned int db_guid, unsigned int pool_id)
{
    mSpawnedCreatures.insert(db_guid);
    ++mSpawnedPools[pool_id];
}

template<>
void SpawnedPoolData::AddSpawn<battle::object::GameObject>(unsigned int db_guid, unsigned int pool_id)
{
    mSpawnedGameobjects.insert(db_guid);
    ++mSpawnedPools[pool_id];
}

template<>
void SpawnedPoolData::AddSpawn<Pool>(unsigned int sub_pool_id, unsigned int pool_id)
{
    mSpawnedPools[sub_pool_id] = 0;
    ++mSpawnedPools[pool_id];
}

template<>
void SpawnedPoolData::RemoveSpawn<battle::object::Creature>(unsigned int db_guid, unsigned int pool_id)
{
    mSpawnedCreatures.erase(db_guid);
    unsigned int& val = mSpawnedPools[pool_id];
    if (val > 0)
    {
        --val;
    }
}

template<>
void SpawnedPoolData::RemoveSpawn<battle::object::GameObject>(unsigned int db_guid, unsigned int pool_id)
{
    mSpawnedGameobjects.erase(db_guid);
    unsigned int& val = mSpawnedPools[pool_id];
    if (val > 0)
    {
        --val;
    }
}

template<>
void SpawnedPoolData::RemoveSpawn<Pool>(unsigned int sub_pool_id, unsigned int pool_id)
{
    mSpawnedPools.erase(sub_pool_id);
    unsigned int& val = mSpawnedPools[pool_id];
    if (val > 0)
    {
        --val;
    }
}

////////////////////////////////////////////////////////////
// Methods of class PoolObject
template<>
void PoolObject::CheckEventLinkAndReport<battle::object::Creature>(unsigned int poolId, short event_id, std::map<unsigned int, short> const& creature2event, std::map<unsigned int, short> const& /*go2event*/) const
{
    std::map<unsigned int, short>::const_iterator itr = creature2event.find(guid);
    if (itr == creature2event.end() || itr->second != event_id)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Creature (GUID: {}) expected to be listed in `game_event_creature` for event {} as part pool {}", guid, event_id, poolId));
    }
}

template<>
void PoolObject::CheckEventLinkAndReport<battle::object::GameObject>(unsigned int poolId, short event_id, std::map<unsigned int, short> const& /*creature2event*/, std::map<unsigned int, short> const& go2event) const
{
    std::map<unsigned int, short>::const_iterator itr = go2event.find(guid);
    if (itr == go2event.end() || itr->second != event_id)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Gameobject (GUID: {}) expected to be listed in `game_event_gameobject` for event {} as part pool {}", guid, event_id, poolId));
    }
}

template<>
void PoolObject::CheckEventLinkAndReport<Pool>(unsigned int /*poolId*/, short event_id, std::map<unsigned int, short> const& creature2event, std::map<unsigned int, short> const& go2event) const
{
    PoolManager::Instance().CheckEventLinkAndReport(guid, event_id, creature2event, go2event);
}

////////////////////////////////////////////////////////////
// Methods of template class PoolGroup

// Method to add a gameobject/creature guid to the proper list depending on pool type and chance value
template <class T>
void PoolGroup<T>::AddEntry(PoolObject& poolitem, unsigned int maxentries)
{
    if (poolitem.chance != 0 && maxentries == 1)
    {
        ExplicitlyChanced.push_back(poolitem);
    }
    else
    {
        EqualChanced.push_back(poolitem);
    }
}

// Method to check the chances are proper in this object pool
template <class T>
bool PoolGroup<T>::CheckPool() const
{
    if (EqualChanced.empty())
    {
        float chance = 0;
        for (unsigned int i = 0; i < ExplicitlyChanced.size(); ++i)
        {
            chance += ExplicitlyChanced[i].chance;
        }
        if (chance != 100 && chance != 0)
        {
            return false;
        }
    }
    return true;
}

// Method to check event linking
template <class T>
void PoolGroup<T>::CheckEventLinkAndReport(unsigned short event_id, std::map<unsigned int, short> const& creature2event, std::map<unsigned int, short> const& go2event) const
{
    for (unsigned int i = 0; i < EqualChanced.size(); ++i)
    {
        EqualChanced[i].template CheckEventLinkAndReport<T>(poolId, event_id, creature2event, go2event);
    }

    for (unsigned int i = 0; i < ExplicitlyChanced.size(); ++i)
    {
        ExplicitlyChanced[i].template CheckEventLinkAndReport<T>(poolId, event_id, creature2event, go2event);
    }
}

template <class T>
void PoolGroup<T>::SetExcludeObject(unsigned int guid, bool state)
{
    for (unsigned int i = 0; i < EqualChanced.size(); ++i)
    {
        if (EqualChanced[i].guid == guid)
        {
            EqualChanced[i].exclude = state;
            return;
        }
    }

    for (unsigned int i = 0; i < ExplicitlyChanced.size(); ++i)
    {
        if (ExplicitlyChanced[i].guid == guid)
        {
            ExplicitlyChanced[i].exclude = state;
            return;
        }
    }
}

template <class T>
PoolObject* PoolGroup<T>::RollOne(SpawnedPoolData& spawns, unsigned int triggerFrom)
{
    if (!ExplicitlyChanced.empty())
    {
        float roll = (float)util::RandChance();

        for (unsigned int i = 0; i < ExplicitlyChanced.size(); ++i)
        {
            roll -= ExplicitlyChanced[i].chance;
            // Triggering object is marked as spawned at this time and can be also rolled (respawn case)
            // so this need explicit check for this case
            if (roll < 0 && !ExplicitlyChanced[i].exclude && (ExplicitlyChanced[i].guid == triggerFrom || !spawns.IsSpawnedObject<T>(ExplicitlyChanced[i].guid)))
            {
                return &ExplicitlyChanced[i];
            }
        }
    }

    if (!EqualChanced.empty())
    {
        int index = util::IRand(0, (int)EqualChanced.size() - 1);
        // Triggering object is marked as spawned at this time and can be also rolled (respawn case)
        // so this need explicit check for this case
        if (!EqualChanced[index].exclude && (EqualChanced[index].guid == triggerFrom || !spawns.IsSpawnedObject<T>(EqualChanced[index].guid)))
        {
            return &EqualChanced[index];
        }
    }

    return nullptr;
}

// Main method to despawn a creature or gameobject in a pool
// If no guid is passed, the pool is just removed (event end case)
// If guid is filled, cache will be used and no removal will occur, it just fill the cache
template<class T>
void PoolGroup<T>::DespawnObject(MapPersistentState& mapState, unsigned int guid)
{
    for (size_t i = 0; i < EqualChanced.size(); ++i)
    {
        // if spawned
        if (mapState.GetSpawnedPoolData().IsSpawnedObject<T>(EqualChanced[i].guid))
        {
            // any or specially requested
            if (!guid || EqualChanced[i].guid == guid)
            {
                Despawn1Object(mapState, EqualChanced[i].guid);
                mapState.GetSpawnedPoolData().RemoveSpawn<T>(EqualChanced[i].guid, poolId);
            }
        }
    }

    for (size_t i = 0; i < ExplicitlyChanced.size(); ++i)
    {
        // spawned
        if (mapState.GetSpawnedPoolData().IsSpawnedObject<T>(ExplicitlyChanced[i].guid))
        {
            // any or specially requested
            if (!guid || ExplicitlyChanced[i].guid == guid)
            {
                Despawn1Object(mapState, ExplicitlyChanced[i].guid);
                mapState.GetSpawnedPoolData().RemoveSpawn<T>(ExplicitlyChanced[i].guid, poolId);
            }
        }
    }
}

// Method that is actualy doing the removal job on one creature
template<>
void PoolGroup<battle::object::Creature>::Despawn1Object(MapPersistentState& mapState, unsigned int guid)
{
    if (auto const* data = mt::CreatureData::GetElement(guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
        {
            dataMapState->RemoveCreatureFromGrid(guid, data);

            if (Map* dataMap = dataMapState->GetMap())
                if (auto* pCreature = dataMap->GetCreature(data->GetObjectGuid(guid)))
                {
                    pCreature->AddObjectToRemoveList();
                }
        }
    }
}

// Same on one gameobject
template<>
void PoolGroup<battle::object::GameObject>::Despawn1Object(MapPersistentState& mapState, unsigned int guid)
{
    if (auto const* data = mt::GameObjectData::GetElement(guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
        {
            dataMapState->RemoveGameobjectFromGrid(guid, data);

            if (Map* dataMap = dataMapState->GetMap())
                if (auto pGameobject = dataMap->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, guid)))
                {
                    pGameobject->AddObjectToRemoveList();
                }
        }
    }
}

// Same on one pool
template<>
void PoolGroup<Pool>::Despawn1Object(MapPersistentState& mapState, unsigned int child_pool_id)
{
    PoolManager::Instance().DespawnPool(mapState, child_pool_id);
}

// Method for a pool only to remove any found record causing a circular dependency loop
template<>
void PoolGroup<Pool>::RemoveOneRelation(unsigned short child_pool_id)
{
    for (PoolObjectList::iterator itr = ExplicitlyChanced.begin(); itr != ExplicitlyChanced.end(); ++itr)
    {
        if (itr->guid == child_pool_id)
        {
            ExplicitlyChanced.erase(itr);
            break;
        }
    }
    for (PoolObjectList::iterator itr = EqualChanced.begin(); itr != EqualChanced.end(); ++itr)
    {
        if (itr->guid == child_pool_id)
        {
            EqualChanced.erase(itr);
            break;
        }
    }
}

template <class T>
void PoolGroup<T>::SpawnObject(MapPersistentState& mapState, unsigned int limit, unsigned int triggerFrom, bool instantly)
{
    SpawnedPoolData& spawns = mapState.GetSpawnedPoolData();

    unsigned int lastDespawned = 0;
    int count = limit - spawns.GetSpawnedObjects(poolId);

    // If triggered from some object respawn this object is still marked as spawned
    // and also counted into m_SpawnedPoolAmount so we need increase count to be
    // spawned by 1
    if (triggerFrom)
    {
        if (spawns.IsSpawnedObject<T>(triggerFrom))
        {
            ++count;
        }
        else
        {
            triggerFrom = 0;
        }
    }

    // This will try to spawn the rest of pool, not guaranteed
    for (int i = 0; i < count; ++i)
    {
        PoolObject* obj = RollOne(spawns, triggerFrom);
        if (!obj)
        {
            continue;
        }
        if (obj->guid == lastDespawned)
        {
            continue;
        }

        if (obj->guid == triggerFrom)
        {
            CFT_ASSERT(spawns.IsSpawnedObject<T>(obj->guid));
            CFT_ASSERT(spawns.GetSpawnedObjects(poolId) > 0);
            ReSpawn1Object(mapState, obj);
            triggerFrom = 0;
            continue;
        }

        spawns.AddSpawn<T>(obj->guid, poolId);
        Spawn1Object(mapState, obj, instantly);

        if (triggerFrom)
        {
            // One spawn one despawn no count increase
            DespawnObject(mapState, triggerFrom);
            lastDespawned = triggerFrom;
            triggerFrom = 0;
        }
    }
}

// Method that is actualy doing the spawn job on 1 creature
template <>
void PoolGroup<battle::object::Creature>::Spawn1Object(MapPersistentState& mapState, PoolObject* obj, bool instantly)
{
    if (auto const* data = mt::CreatureData::GetElement(obj->guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
        {
            dataMapState->AddCreatureToGrid(obj->guid, data);

            Map* dataMap = dataMapState->GetMap();

            // We use spawn coords to spawn
            if (dataMap && dataMap->IsLoaded(data->posX, data->posY))
            {
                auto pCreature = new battle::object::Creature();
                // DEBUG_LOG("Spawning creature %u",obj->guid);
                if (!pCreature->LoadFromDB(obj->guid, dataMap))
                {
                    delete pCreature;
                    return;
                }
                else
                {
                    // if new spawn replaces a just despawned creature, not instantly spawn but set respawn timer
                    if (!instantly)
                    {
                        pCreature->SetRespawnTime(pCreature->GetRespawnDelay());
                        if (World::Instance().getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY) || pCreature->IsWorldBoss())
                        {
                            pCreature->SaveRespawnTime();
                        }
                    }
                    dataMap->Add(pCreature);
                }
            }
            // for not loaded grid just update respawn time (avoid work for instances until implemented support)
            else if (!instantly)
            {
                dataMapState->SaveCreatureRespawnTime(obj->guid, time(NULL) + data->spawntimesecs);
            }
        }
    }
}

// Same for 1 gameobject
template <>
void PoolGroup<battle::object::GameObject>::Spawn1Object(MapPersistentState& mapState, PoolObject* obj, bool instantly)
{
    if (auto const* data = mt::GameObjectData::GetElement(obj->guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
        {
            dataMapState->AddGameobjectToGrid(obj->guid, data);

            Map* dataMap = dataMapState->GetMap();

            // We use spawn coords to spawn
            if (dataMap && dataMap->IsLoaded(data->posX, data->posY))
            {
                auto pGameobject = new battle::object::GameObject;
                // DEBUG_LOG("Spawning gameobject %u", obj->guid);
                if (!pGameobject->LoadFromDB(obj->guid, dataMap))
                {
                    delete pGameobject;
                    return;
                }
                else
                {
                    if (pGameobject->isSpawnedByDefault())
                    {
                        // if new spawn replaces a just despawned object, not instantly spawn but set respawn timer
                        if (!instantly)
                        {
                            pGameobject->SetRespawnTime(pGameobject->GetRespawnDelay());
                            if (World::Instance().getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY))
                            {
                                pGameobject->SaveRespawnTime();
                            }
                        }
                        dataMap->Add(pGameobject);
                    }
                }
            }
            // for not loaded grid just update respawn time (avoid work for instances until implemented support)
            else if (!instantly)
            {
                // for spawned by default object only
                if (data->spawntimesecs >= 0)
                {
                    dataMapState->SaveGORespawnTime(obj->guid, time(NULL) + data->spawntimesecs);
                }
            }
        }
    }
}

// Same for 1 pool
template <>
void PoolGroup<Pool>::Spawn1Object(MapPersistentState& mapState, PoolObject* obj, bool instantly)
{
    PoolManager::Instance().SpawnPool(mapState, obj->guid, instantly);
}

// Method that does the respawn job on the specified creature
template <>
void PoolGroup<battle::object::Creature>::ReSpawn1Object(MapPersistentState& mapState, PoolObject* obj)
{
    if (auto const* data = mt::CreatureData::GetElement(obj->guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
            if (Map* dataMap = dataMapState->GetMap())
                if (auto pCreature = dataMap->GetCreature(data->GetObjectGuid(obj->guid)))
                {
                    pCreature->GetMap()->Add(pCreature);
                }
    }
}

// Method that does the respawn job on the specified gameobject
template <>
void PoolGroup<battle::object::GameObject>::ReSpawn1Object(MapPersistentState& mapState, PoolObject* obj)
{
    if (auto const* data = mt::GameObjectData::GetElement(obj->guid))
    {
        // for non-instanceable maps pool spawn can be at different map from provided mapState
        if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : MapPersistentStateManager::Instance().GetPersistentState(data->mapid, 0))
            if (Map* dataMap = dataMapState->GetMap())
                if (auto pGameobject = dataMap->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, obj->guid)))
                {
                    pGameobject->GetMap()->Add(pGameobject);
                }
    }
}

// Nothing to do for a child Pool
template <>
void PoolGroup<Pool>::ReSpawn1Object(MapPersistentState& /*mapState*/, PoolObject* /*obj*/)
{
}


////////////////////////////////////////////////////////////
// Methods of class PoolManager

PoolManager::PoolManager()
{
}

// Check listing all pool spawns in single instanceable map or only in non-instanceable maps
// This applied to all pools have common mother pool
struct PoolMapChecker
{
    PoolManager::PoolTemplateDataMap& m_poolTemplates;

    explicit PoolMapChecker(PoolManager::PoolTemplateDataMap& poolTemplates) : m_poolTemplates(poolTemplates) {}

    bool CheckAndRemember(unsigned int mapid, unsigned int pool_id, char const* tableName, char const* elementName, unsigned int guid)
    {
        dbc::MapEntry const* mapEntry = dbc::MapEntry::GetElement(mapid);
        if (!mapEntry)
        {
            return false;
        }

        dbc::MapEntry const* poolMapEntry = m_poolTemplates[pool_id].mapEntry;

        // if not listed then just remember
        if (!poolMapEntry)
        {
            m_poolTemplates[pool_id].mapEntry = mapEntry;
            return true;
        }

        // if at same map, then all ok
        if (poolMapEntry == mapEntry)
        {
            return true;
        }

        // pool spawns must be at single instanceable map
        if (mapEntry->Instanceable())
        {
            cftf::loger::SysLog::Instance().Error(std::format("`{}` has {} ({}) spawned at instanceable map {} when one or several other spawned at different map {} in pool id {}, skipped.",
                tableName, elementName, guid, mapid, poolMapEntry->MapID, pool_id));
            return false;
        }

        // pool spawns must be at single instanceable map
        if (poolMapEntry->Instanceable())
        {
            cftf::loger::SysLog::Instance().Error(std::format("`{}` has {} ({}) spawned at map {} when one or several other spawned at different instanceable map {} in pool id {}, skipped.",
                tableName, elementName, guid, mapid, poolMapEntry->MapID, pool_id));
            return false;
        }
        // pool spawns can be at different non-instanceable maps
        return true;
    }
};

void PoolManager::LoadFromDB()
{
    if (mt::PoolTemplate::GetSize() <= 0) {
        cftf::loger::SysLog::Instance().Error("Table pool_template is empty.");
        return;
    }
    max_pool_id = mt::PoolTemplate::GetMaxPoolId();
    mPoolTemplate.resize(mt::PoolTemplate::GetMaxPoolId() + 1);
    mt::PoolTemplate::Traverse(
        [this](const mt::PoolTemplate* meta, bool& stop) -> bool
        {
            PoolTemplateData& pPoolTemplate = mPoolTemplate[meta->entry];
            pPoolTemplate.MaxLimit = meta->max_limit;
            pPoolTemplate.description = meta->description;
            pPoolTemplate.AutoSpawn = true;          // will update and later data loading
            return true;
        }
    );
    cftf::loger::SysLog::Instance().Info(std::format("Loaded {} objects pools", mt::PoolTemplate::GetSize()));

    PoolMapChecker mapChecker(mPoolTemplate);

    mPoolCreatureGroups.resize(mt::PoolTemplate::GetMaxPoolId() + 1);
    mCreatureSearchMap.clear();
    mt::PoolCreature::Traverse(
        [this, &mapChecker](const mt::PoolCreature* meta, bool& stop) -> bool
        {
            auto const* data = mt::CreatureData::GetElement(meta->guid);
            if (!data)
            {
                cftf::loger::SysLog::Instance().Deubg(std::format("`pool_creature` has a non existing creature spawn (GUID: {}) defined for pool id ({}), skipped.", meta->guid, meta->pool_entry));
                return true;
            }
            if (meta->pool_entry > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature` pool id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->pool_entry));
                return true;
            }
            if (meta->chance < 0 || meta->chance > 100)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature` has an invalid chance ({}) for creature guid ({}) in pool id ({}), skipped.", meta->chance, meta->guid, meta->pool_entry));
                return true;
            }

            if (!mapChecker.CheckAndRemember(data->mapid, meta->pool_entry, "pool_creature", "creature guid", meta->guid))
            {
                return true;
            }
            PoolTemplateData* pPoolTemplate = &mPoolTemplate[meta->pool_entry];
            PoolObject plObject = PoolObject(meta->guid, meta->chance);
            PoolGroup<battle::object::Creature>& cregroup = mPoolCreatureGroups[meta->pool_entry];
            cregroup.SetPoolId(meta->pool_entry);
            cregroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
            SearchPair p(meta->guid, meta->pool_entry);
            mCreatureSearchMap.insert(p);
            return true;
        }
    );
    cftf::loger::SysLog::Instance().Info(std::format("Loaded {} creatures in pools from `pool_creature", mt::PoolCreature::GetSize()));

    mt::PoolCreatureTemplate::Traverse(
        [this, &mapChecker](const mt::PoolCreatureTemplate* meta, bool& stop) -> bool
        {

            auto const* data = mt::CreatureData::GetElement(meta->guid);
            if (!data)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature_template` has a non existing creature spawn (GUID: {} Entry: {}) defined for pool id ({}), skipped.", meta->guid, meta->id, meta->pool_entry));
                return true;
            }
            if (meta->pool_entry > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature_template` pool id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->pool_entry));
                return true;
            }
            if (meta->chance < 0 || meta->chance > 100)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature_template` has an invalid chance ({}) for creature (Guid {} Entry {}) in pool id ({}), skipped.", meta->chance, meta->guid, meta->id, meta->pool_entry));
                return true;
            }

            if (unsigned short alt_pool_id = IsPartOfAPool<battle::object::Creature>(meta->guid))
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_creature` has guid %u for pool %u that already added to pool %u from `pool_creature_template` for creature entry %u, skipped.",
                    meta->guid, meta->pool_entry, alt_pool_id, meta->id));
                return true;
            }

            if (!mapChecker.CheckAndRemember(data->mapid, meta->pool_entry, "pool_creature_template", "creature guid", meta->guid))
            {
                return true;
            }

            PoolTemplateData* pPoolTemplate = &mPoolTemplate[meta->pool_entry];
            PoolObject plObject = PoolObject(meta->guid, meta->chance);
            PoolGroup<battle::object::Creature>& cregroup = mPoolCreatureGroups[meta->pool_entry];
            cregroup.SetPoolId(meta->pool_entry);
            cregroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
            SearchPair p(meta->guid, meta->pool_entry);
            mCreatureSearchMap.insert(p);
            return true;
        });
    cftf::loger::SysLog::Instance().Info(std::format("Loaded {} creatures in pools from `pool_creature_template`", mt::PoolCreatureTemplate::GetSize()));

    mPoolGameobjectGroups.resize(mt::PoolTemplate::GetMaxPoolId() + 1);
    mGameobjectSearchMap.clear();
    mt::PoolGameObject::Traverse(
        [this, &mapChecker](const mt::PoolGameObject* meta, bool& stop) -> bool
        {
            auto const* data = mt::GameObjectData::GetElement(meta->guid);
            if (!data)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject` has a non existing gameobject spawn (GUID: {}) defined for pool id ({}), skipped.", meta->guid, meta->pool_entry));
                return true;
            }
            if (meta->pool_entry > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject` pool id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->pool_entry));
                return true;
            }
            if (meta->chance < 0 || meta->chance > 100)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject` has an invalid chance ({}) for gameobject guid ({}) in pool id ({}), skipped.", meta->chance, meta->guid, meta->pool_entry));
                return true;
            }

            if (!mapChecker.CheckAndRemember(data->mapid, meta->pool_entry, "pool_gameobject", "gameobject guid", meta->guid))
            {
                return true;
            }
            PoolTemplateData* pPoolTemplate = &mPoolTemplate[meta->pool_entry];
            PoolObject plObject = PoolObject(meta->guid, meta->chance);
            PoolGroup<battle::object::GameObject>& gogroup = mPoolGameobjectGroups[meta->pool_entry];
            gogroup.SetPoolId(meta->pool_entry);
            gogroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
            SearchPair p(meta->guid, meta->pool_entry);
            mGameobjectSearchMap.insert(p);
            return true;
        });

    cftf::loger::SysLog::Instance().Info(std::format("Loaded {} gameobject in pools from `pool_gameobject`", mt::PoolGameObject::GetSize()));

    mt::PoolGameObjectTemplate::Traverse(
        [this, &mapChecker](const mt::PoolGameObjectTemplate* meta, bool& stop) -> bool
        {
            auto const* data = mt::GameObjectData::GetElement(meta->guid);
            if (!data)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject_template` has a non existing gameobject spawn (GUID: {} Entry {}) defined for pool id ({}), skipped.", meta->guid, meta->entry_id, meta->pool_entry));
                return true;
            }
            if (meta->pool_entry > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject_template` pool id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->pool_entry));
                return true;
            }
            if (meta->chance < 0 || meta->chance > 100)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject_template` has an invalid chance ({}) for gameobject (Guid {} Entry {}) in pool id ({}), skipped.", meta->chance, meta->guid, meta->entry_id, meta->pool_entry));
                return true;
            }

            if (unsigned short alt_pool_id = IsPartOfAPool<battle::object::GameObject>(meta->guid))
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_gameobject` has guid {} for pool {} that already added to pool {} from `pool_gameobject_template` for gameobject entry {}, skipped.",
                    meta->guid, meta->pool_entry, alt_pool_id, meta->entry_id));
                return true;
            }

            if (!mapChecker.CheckAndRemember(data->mapid, meta->pool_entry, "pool_gameobject_template", "gameobject guid", meta->guid))
            {
                return true;
            }
            PoolTemplateData* pPoolTemplate = &mPoolTemplate[meta->pool_entry];
            PoolObject plObject = PoolObject(meta->guid, meta->chance);
            PoolGroup<battle::object::GameObject>& gogroup = mPoolGameobjectGroups[meta->pool_entry];
            gogroup.SetPoolId(meta->pool_entry);
            gogroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
            SearchPair p(meta->guid, meta->pool_entry);
            mGameobjectSearchMap.insert(p);
            return true;
        });
    cftf::loger::SysLog::Instance().Info(std::format("Loaded {} gameobject in pools from `pool_gameobject_template", mt::PoolGameObjectTemplate::GetSize()));

    mPoolPoolGroups.resize(mt::PoolTemplate::GetMaxPoolId() + 1);
    mt::PoolPool::Traverse(
        [this, &mapChecker](const mt::PoolPool* meta, bool& stop) -> bool
        {
            if (meta->mother_pool > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_pool` mother_pool id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->mother_pool));
                return true;
            }
            if (meta->pool_id > mt::PoolTemplate::GetMaxPoolId())
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_pool` included pool_id ({}) is out of range compared to max pool id in `pool_template`, skipped.", meta->pool_id));
                return true;
            }
            if (meta->mother_pool == meta->pool_id)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_pool` pool_id ({}) includes itself, dead-lock detected, skipped.", meta->pool_id));
                return true;
            }
            if (meta->chance < 0 || meta->chance > 100)
            {
                cftf::loger::SysLog::Instance().Error(std::format("`pool_pool` has an invalid chance (%f) for pool id (%u) in mother pool id (%i), skipped.", meta->chance, meta->pool_id, meta->mother_pool));
                return true;
            }
            PoolTemplateData* pPoolTemplateMother = &mPoolTemplate[meta->mother_pool];
            PoolObject plObject = PoolObject(meta->pool_id, meta->chance);
            PoolGroup<Pool>& plgroup = mPoolPoolGroups[meta->mother_pool];
            plgroup.SetPoolId(meta->mother_pool);
            plgroup.AddEntry(plObject, pPoolTemplateMother->MaxLimit);
            SearchPair p(meta->pool_id, meta->mother_pool);
            mPoolSearchMap.insert(p);
            return true;
        });
    {
        int count = 0;
        // Now check for circular reference
        for (unsigned short i = 0; i < max_pool_id; ++i)
        {
            std::set<unsigned short> checkedPools;
            for (SearchMap::iterator poolItr = mPoolSearchMap.find(i); poolItr != mPoolSearchMap.end(); poolItr = mPoolSearchMap.find(poolItr->second))
            {
                // if child pool not have map data then it empty or have not checked child then will checked and all line later
                if (auto const* childMapEntry = mPoolTemplate[poolItr->first].mapEntry)
                {
                    if (!mapChecker.CheckAndRemember(childMapEntry->MapID, poolItr->second, "pool_pool", "pool with creature/gameobject", poolItr->first))
                    {
                        mPoolPoolGroups[poolItr->second].RemoveOneRelation(poolItr->first);
                        mPoolSearchMap.erase(poolItr);
                        --count;
                        break;
                    }
                }

                checkedPools.insert(poolItr->first);
                if (checkedPools.find(poolItr->second) != checkedPools.end())
                {
                    std::ostringstream ss;
                    ss << "The pool(s) ";
                    for (std::set<unsigned short>::const_iterator itr = checkedPools.begin(); itr != checkedPools.end(); ++itr)
                    {
                        ss << *itr << " ";
                    }
                    ss << "create(s) a circular reference, which can cause the server to freeze.\nRemoving the last link between mother pool "
                        << poolItr->first << " and child pool " << poolItr->second;
                    cftf::loger::SysLog::Instance().Error(ss.str());
                    mPoolPoolGroups[poolItr->second].RemoveOneRelation(poolItr->first);
                    mPoolSearchMap.erase(poolItr);
                    --count;
                    break;
                }
            }
        }
        cftf::loger::SysLog::Instance().Info(std::format("Loaded {} pools in mother pools", count));
    }

    // check chances integrity
    for (unsigned short pool_entry = 0; pool_entry < mPoolTemplate.size(); ++pool_entry)
    {
        if (mPoolTemplate[pool_entry].AutoSpawn)
        {
            if (!CheckPool(pool_entry))
            {
                cftf::loger::SysLog::Instance().Error(std::format("Pool Id ({}) has all creatures or gameobjects with explicit chance sum <>100 and no equal chance defined. The pool system can not pick one to spawn.", pool_entry));
                mPoolTemplate[pool_entry].AutoSpawn = false;
            }
        }
    }
    if (World::Instance().getConfig(CONFIG_BOOL_AUTOPOOLING_MINING_ENABLE))
    {

        // autocreate mining pools
        mPoolTemplate.resize(max_pool_id + 3486 + 533);  //values are hardcoded for max zoneID and max MapID it would be better to read max IDs from the .dbc files
        mPoolCreatureGroups.resize(max_pool_id + 3486 + 533);
        mPoolGameobjectGroups.resize(max_pool_id + 3486 + 533);
        mPoolPoolGroups.resize(max_pool_id + 3486 + 533);

        unsigned int max_autopool_entry = (max_pool_id + 3486 + 533);
        for (unsigned short pool_entry = max_pool_id + 1; pool_entry < max_autopool_entry; ++pool_entry)
        {
            PoolTemplateData& pPoolTemplate = mPoolTemplate[pool_entry];
            pPoolTemplate.MaxLimit = 0;
            std::ostringstream sZone;
            sZone << "autopool zone " << pool_entry;
            pPoolTemplate.description = sZone.str();
            pPoolTemplate.AutoSpawn = true;          // will update and later data loading
        }

        int count = 0;
        cftf::mysql::DBPool::Instance().RawQuery(
            int(DataSource_e::World),
            "SELECT `gameobject`.`guid`, `gameobject`.`id`, `map`, `position_x`, `position_y`, `position_z`,"
            //   6                          7
            "`pool_gameobject`.`pool_entry`, `pool_gameobject_template`.`pool_entry` "
            "FROM `gameobject` "
            "LEFT OUTER JOIN `pool_gameobject` ON `gameobject`.`guid` = `pool_gameobject`.`guid` "
            "LEFT OUTER JOIN `pool_gameobject_template` ON `gameobject`.`id` = `pool_gameobject_template`.`id`",
            {},
            [this, &count, &mapChecker](const std::shared_ptr<cftf::mysql::QueryRsp> rsp)
            {
                if (!rsp->IsOk()) {
                    CFT_ABORT();
                }
                if (rsp->GetDataSet()->IsEof()) {
                    cftf::loger::SysLog::Instance().Error(">> Loaded 0 gameobjects. DB table `gameobject` is empty.");
                }
                else {
                    while (rsp->GetDataSet()->IsEof()) {                        
                        unsigned int guid = rsp->GetDataSet()->GetByFieldIdx(0)->Get<unsigned int>();
                        unsigned int entry = rsp->GetDataSet()->GetByFieldIdx(1)->Get<unsigned int>();
                        unsigned int map = rsp->GetDataSet()->GetByFieldIdx(2)->Get<unsigned int>();
                        float posX = rsp->GetDataSet()->GetByFieldIdx(3)->Get<float>();
                        float posY = rsp->GetDataSet()->GetByFieldIdx(4)->Get<float>();
                        float posZ = rsp->GetDataSet()->GetByFieldIdx(5)->Get<float>();

                        short GuidPoolId = rsp->GetDataSet()->GetByFieldIdx(6)->Get<short>();
                        short EntryPoolId = rsp->GetDataSet()->GetByFieldIdx(7)->Get<short>();

                        if (GuidPoolId != 0 || EntryPoolId != 0) // if not this is in the pool system already
                        {
                            continue;
                        }
                        auto const* goinfo = mt::GameObjectInfo::GetElement(entry);
                        if (goinfo->type != GAMEOBJECT_TYPE_CHEST)
                        {
                            continue;
                        }

                        if (goinfo->chest.minSuccessOpens != 0 && goinfo->chest.maxSuccessOpens > goinfo->chest.minSuccessOpens) //in this case it is a mineral vein
                        {
                            unsigned int zone_id;
                            unsigned short pool_id;
                            if (map == 0 || map == 1)
                            {
                                zone_id = TerrainManager::Instance().LoadTerrain(map)->GetZoneId(posX, posY, posZ);
                                pool_id = zone_id + max_pool_id;
                            }
                            else
                            {
                                zone_id = map;
                                pool_id = zone_id + max_pool_id + 3486; //3486 zero value for maxzoneID
                            }

                            //PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id];

                            PoolObject plObject = PoolObject(guid, 0);
                            PoolGroup<battle::object::GameObject>& gogroup = mPoolGameobjectGroups[pool_id];
                            gogroup.SetPoolId(pool_id);
                            gogroup.AddEntry(plObject, 0);
                            SearchPair p(guid, pool_id);
                            mGameobjectSearchMap.insert(p);

                            if (!mapChecker.CheckAndRemember(map, pool_id, "pool_gameobject", "gameobject guid", guid))
                            {
                                continue;
                            }

                            ++count;

#if 0
                            cftf::loger::SysLog::Instance().Error(std::format("UPDATE `gameobject` SET `zone_id`={}, `area_id`={} WHERE `guid`={};", zoneId, areaId, guid));
#endif
                        }
                        rsp->GetDataSet()->Next();
                    }
                }
            }
        )->Await();    
        for (unsigned short pool_entry = max_pool_id + 1; pool_entry < max_autopool_entry; ++pool_entry)
        {
            unsigned int poolsize;
            PoolTemplateData& pPoolTemplate = mPoolTemplate[pool_entry];
            PoolGroup<battle::object::GameObject>& gogroup = mPoolGameobjectGroups[pool_entry];
            poolsize = (decltype(poolsize))gogroup.size();
            pPoolTemplate.MaxLimit = (poolsize * CONFIG_UINT32_RATE_MINING_AUTOPOOLING) / 100;
        }
        cftf::loger::SysLog::Instance().Error(std::format(">> Loaded {} mining nodes", count));
    }
}

// The initialize method will spawn all pools not in an event and not in another pool
void PoolManager::Initialize(MapPersistentState* state)
{
    // spawn pools for expected map or for not initialized shared pools state for non-instanceable maps
    for (unsigned short pool_entry = 0; pool_entry < mPoolTemplate.size(); ++pool_entry)
        if (mPoolTemplate[pool_entry].AutoSpawn)
        {
            InitSpawnPool(*state, pool_entry);
        }
}

// Call to spawn a pool, if cache if true the method will spawn only if cached entry is different
// If it's same, the creature is respawned only (added back to map)
template<>
void PoolManager::SpawnPoolGroup<battle::object::Creature>(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid, bool instantly)
{
    if (!mPoolCreatureGroups[pool_id].isEmpty())
    {
        mPoolCreatureGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, db_guid, instantly);
    }
}

// Call to spawn a pool, if cache if true the method will spawn only if cached entry is different
// If it's same, the gameobject is respawned only (added back to map)
template<>
void PoolManager::SpawnPoolGroup<battle::object::GameObject>(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid, bool instantly)
{
    if (!mPoolGameobjectGroups[pool_id].isEmpty())
    {
        mPoolGameobjectGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, db_guid, instantly);
    }
}

// Call to spawn a pool, if cache if true the method will spawn only if cached entry is different
// If it's same, the pool is respawned only
template<>
void PoolManager::SpawnPoolGroup<Pool>(MapPersistentState& mapState, unsigned short pool_id, unsigned int sub_pool_id, bool instantly)
{
    if (!mPoolPoolGroups[pool_id].isEmpty())
    {
        mPoolPoolGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, sub_pool_id, instantly);
    }
}

/*!
    \param instantly defines if (leaf-)objects are spawned instantly or with fresh respawn timer */
void PoolManager::SpawnPool(MapPersistentState& mapState, unsigned short pool_id, bool instantly)
{
    SpawnPoolGroup<Pool>(mapState, pool_id, 0, instantly);
    SpawnPoolGroup<battle::object::GameObject>(mapState, pool_id, 0, instantly);
    SpawnPoolGroup<battle::object::Creature>(mapState, pool_id, 0, instantly);
}

// Call to despawn a pool, all gameobjects/creatures in this pool are removed
void PoolManager::DespawnPool(MapPersistentState& mapState, unsigned short pool_id)
{
    if (!mPoolCreatureGroups[pool_id].isEmpty())
    {
        mPoolCreatureGroups[pool_id].DespawnObject(mapState);
    }

    if (!mPoolGameobjectGroups[pool_id].isEmpty())
    {
        mPoolGameobjectGroups[pool_id].DespawnObject(mapState);
    }

    if (!mPoolPoolGroups[pool_id].isEmpty())
    {
        mPoolPoolGroups[pool_id].DespawnObject(mapState);
    }
}

// Method that check chance integrity of the creatures and gameobjects in this pool
bool PoolManager::CheckPool(unsigned short pool_id) const
{
    return pool_id <= max_pool_id &&
        mPoolGameobjectGroups[pool_id].CheckPool() &&
        mPoolCreatureGroups[pool_id].CheckPool() &&
        mPoolPoolGroups[pool_id].CheckPool();
}

// Method that check linking all elements to event
void PoolManager::CheckEventLinkAndReport(unsigned short pool_id, unsigned short event_id, std::map<unsigned int, short> const& creature2event, std::map<unsigned int, short> const& go2event) const
{
    mPoolGameobjectGroups[pool_id].CheckEventLinkAndReport(event_id, creature2event, go2event);
    mPoolCreatureGroups[pool_id].CheckEventLinkAndReport(event_id, creature2event, go2event);
    mPoolPoolGroups[pool_id].CheckEventLinkAndReport(event_id, creature2event, go2event);
}

// Method that exclude some elements from next spawn
template<>
void PoolManager::SetExcludeObject<battle::object::Creature>(unsigned short pool_id, unsigned int db_guid_or_pool_id, bool state)
{
    mPoolCreatureGroups[pool_id].SetExcludeObject(db_guid_or_pool_id, state);
}

template<>
void PoolManager::SetExcludeObject<battle::object::GameObject>(unsigned short pool_id, unsigned int db_guid_or_pool_id, bool state)
{
    mPoolGameobjectGroups[pool_id].SetExcludeObject(db_guid_or_pool_id, state);
}

// Call to update the pool when a gameobject/creature part of pool [pool_id] is ready to respawn
// Here we cache only the creature/gameobject whose guid is passed as parameter
// Then the spawn pool call will use this cache to decide
template<typename T>
void PoolManager::UpdatePool(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid_or_pool_id)
{
    if (unsigned short motherpoolid = IsPartOfAPool<Pool>(pool_id))
    {
        SpawnPoolGroup<Pool>(mapState, motherpoolid, pool_id, false);
    }
    else
    {
        SpawnPoolGroup<T>(mapState, pool_id, db_guid_or_pool_id, false);
    }
}

template void PoolManager::UpdatePool<Pool>(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid_or_pool_id);
template void PoolManager::UpdatePool<battle::object::GameObject>(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid_or_pool_id);
template void PoolManager::UpdatePool<battle::object::Creature>(MapPersistentState& mapState, unsigned short pool_id, unsigned int db_guid_or_pool_id);

struct SpawnPoolInMapsWorker
{
    explicit SpawnPoolInMapsWorker(PoolManager& mgr, unsigned int pool_id, bool instantly)
        : i_mgr(mgr), i_pool_id(pool_id), i_instantly(instantly) {
    }

    void operator()(MapPersistentState* state)
    {
        i_mgr.SpawnPool(*state, i_pool_id, i_instantly);
    }

    PoolManager& i_mgr;
    unsigned int i_pool_id;
    bool i_instantly;
};

// used for calling from global systems when need spawn pool in all appropriate map persistent states
void PoolManager::SpawnPoolInMaps(unsigned short pool_id, bool instantly)
{
    PoolTemplateData& poolTemplate = mPoolTemplate[pool_id];

    // pool no have spawns (base at loading algo
    if (!poolTemplate.mapEntry)
    {
        return;
    }

    SpawnPoolInMapsWorker worker(*this, pool_id, instantly);
    MapPersistentStateManager::Instance().DoForAllStatesWithMapId(poolTemplate.mapEntry->MapID, worker);
}

struct DespawnPoolInMapsWorker
{
    explicit DespawnPoolInMapsWorker(PoolManager& mgr, unsigned int pool_id)
        : i_mgr(mgr), i_pool_id(pool_id) {
    }

    void operator()(MapPersistentState* state)
    {
        i_mgr.DespawnPool(*state, i_pool_id);
    }

    PoolManager& i_mgr;
    unsigned int i_pool_id;
};

// used for calling from global systems when need spawn pool in all appropriate map persistent states
void PoolManager::DespawnPoolInMaps(unsigned short pool_id)
{
    PoolTemplateData& poolTemplate = mPoolTemplate[pool_id];

    // pool no have spawns (base at loading algo
    if (!poolTemplate.mapEntry)
    {
        return;
    }

    DespawnPoolInMapsWorker worker(*this, pool_id);
    MapPersistentStateManager::Instance().DoForAllStatesWithMapId(poolTemplate.mapEntry->MapID, worker);
}

void PoolManager::InitSpawnPool(MapPersistentState& mapState, unsigned short pool_id)
{
    // spawn pool for expected map or for not initialized shared pools state for non-instanceable maps
    if (mPoolTemplate[pool_id].CanBeSpawnedAtMap(mapState.GetMapEntry()))
    {
        SpawnPool(mapState, pool_id, true);
    }
}

template<typename T>
struct UpdatePoolInMapsWorker
{
    explicit UpdatePoolInMapsWorker(PoolManager& mgr, unsigned int pool_id, unsigned int db_guid_or_pool_id)
        : i_mgr(mgr), i_pool_id(pool_id), i_db_guid_or_pool_id(db_guid_or_pool_id) {
    }

    void operator()(MapPersistentState* state)
    {
        i_mgr.UpdatePool<T>(*state, i_pool_id, i_db_guid_or_pool_id);
    }

    PoolManager& i_mgr;
    unsigned int i_pool_id;
    unsigned int i_db_guid_or_pool_id;
};

template<typename T>
void PoolManager::UpdatePoolInMaps(unsigned short pool_id, unsigned int db_guid_or_pool_id)
{
    PoolTemplateData& poolTemplate = mPoolTemplate[pool_id];

    // pool no have spawns (base at loading algo
    if (!poolTemplate.mapEntry)
    {
        return;
    }

    UpdatePoolInMapsWorker<T> worker(*this, pool_id, db_guid_or_pool_id);
    MapPersistentStateManager::Instance().DoForAllStatesWithMapId(poolTemplate.mapEntry->MapID, worker);
}

template void PoolManager::UpdatePoolInMaps<Pool>(unsigned short pool_id, unsigned int db_guid_or_pool_id);
template void PoolManager::UpdatePoolInMaps<battle::object::GameObject>(unsigned short pool_id, unsigned int db_guid_or_pool_id);
template void PoolManager::UpdatePoolInMaps<battle::object::Creature>(unsigned short pool_id, unsigned int db_guid_or_pool_id);
